// const pool = require('../config/db');

// class UserModel {
//   // 根据手机号查询用户
//   static async findByPhone(phone) {
//     const [rows] = await pool.execute('SELECT * FROM users WHERE phone = ?', [phone]);
//     return rows[0];
//   }

//   // 根据ID查询用户
//   static async findById(id) {
//     const [rows] = await pool.execute('SELECT id, phone, nickname, avatar FROM users WHERE id = ?', [id]);
//     return rows[0];
//   }

//   // 创建用户
//   static async create(userData) {
//     const { phone, password, nickname, avatar } = userData;
//     const [result] = await pool.execute(
//       'INSERT INTO users (phone, password, nickname, avatar) VALUES (?, ?, ?, ?)',
//       [phone, password, nickname || `用户${phone.slice(-4)}`, avatar || '']
//     );
//     return result.insertId;
//   }
// }

// module.exports = UserModel;
//userModel.js
const pool = require('../config/db');

class UserModel {
  // 根据手机号查询用户
  static async findByPhone(phone) {
    const [rows] = await pool.execute('SELECT * FROM users WHERE phone = ?', [phone]);
    const user = rows[0];
    if (user) {
      // 确保返回的用户有头像
      user.avatar = this.ensureAvatar(user.avatar, user.nickname, user.phone);
    }
    return user;
  }

  // 根据ID查询用户 - 添加 created_at 字段
  static async findById(id) {
    const [rows] = await pool.execute('SELECT id, phone, nickname, avatar, created_at FROM users WHERE id = ?', [id]);
    const user = rows[0];
    if (user) {
      // 确保返回的用户有头像
      user.avatar = this.ensureAvatar(user.avatar, user.nickname, user.phone);
    }
    return user;
  }

  // 确保用户有头像（新增方法）
  static ensureAvatar(avatar, nickname, phone) {
    if (avatar && avatar.trim() !== '' && avatar !== 'null') {
      return avatar;
    }
    // 生成默认头像
    const displayName = nickname || `用户${phone.slice(-4)}`;
    return `https://ui-avatars.com/api/?name=${encodeURIComponent(displayName)}&background=0D8ABC&color=fff&size=128`;
  }

  // 创建用户
  static async create(userData) {
    const { phone, password, nickname, avatar } = userData;

    // 生成默认头像URL
    const defaultAvatar = avatar || `https://ui-avatars.com/api/?name=${encodeURIComponent(nickname || `用户${phone.slice(-4)}`)}&background=0D8ABC&color=fff&size=128`;

    const [result] = await pool.execute(
      'INSERT INTO users (phone, password, nickname, avatar) VALUES (?, ?, ?, ?)',
      [phone, password, nickname || `用户${phone.slice(-4)}`, defaultAvatar]
    );
    return result.insertId;
  }

  // 更新用户信息
  static async update(id, userData) {
    const { nickname, avatar } = userData;

    const updates = [];
    const params = [];

    if (nickname) {
      updates.push('nickname = ?');
      params.push(nickname);
    }

    if (avatar) {
      updates.push('avatar = ?');
      params.push(avatar);
    }

    if (updates.length === 0) {
      throw new Error('没有要更新的字段');
    }

    params.push(id);

    const [result] = await pool.execute(
      `UPDATE users SET ${updates.join(', ')}, updated_at = CURRENT_TIMESTAMP WHERE id = ?`,
      params
    );

    return result.affectedRows > 0;
  }
}

module.exports = UserModel;